<?php

include('../vendor/imageResize/SimpleImage.php');
$error = "";
$msg = "";
$fileElementName = 'image';
$index = $_GET["index"];
if (!empty($_FILES[$fileElementName]['error']) && !empty($index)) {
    switch ($_FILES[$fileElementName]['error']) {
        case '1':
            $error = 'The uploaded image exceeds the upload_max_filesize directive in php.ini';
            break;
        case '2':
            $error = 'The uploaded image exceeds the MAX_FILE_SIZE directive that was specified in the HTML form';
            break;
        case '3':
            $error = 'The uploaded image was only partially uploaded';
            break;
//        case '4':
//            $error = 'No image was uploaded.';
//            break;
        case '6':
            $error = 'Missing a temporary folder';
            break;
        case '7':
            $error = 'Failed to write image to disk';
            break;
        case '8':
            $error = 'Image upload stopped by extension';
            break;
//        case '999':
//        default:
//            $error = 'No error code avaiable';
    }
} elseif ((empty($_FILES[$fileElementName]['tmp_name']) || $_FILES[$fileElementName]['tmp_name'] == 'none') && !empty($index)) {
    
} elseif ($_FILES[$fileElementName]["type"] == "image/gif" || $_FILES[$fileElementName]["type"] == "image/jpeg" ||
        $_FILES[$fileElementName]["type"] == "image/pjpeg" || $_FILES[$fileElementName]["type"] == "image/png") {
//$error = $_FILES[$fileElementName]["error"];
//      move_uploaded_file($_FILES[$fileElementName]['tmp_name'], "../../products/product" . $index . ".jpg");
    $image = new SimpleImage();
    $image->load($_FILES[$fileElementName]['tmp_name']);
    if($image->getWidth()>1280){
        $image->resizeToWidth(1280);
    }
    if($image->getHeight()>800){
        $image->resizeToHeight(800);
    }
    $image->save("../../products/product" . $index . ".jpg");
    @unlink($_FILES[$fileElementName]);
} else {
    $error = 'JPG or GIF or PNG image files only.';
}
echo "{";
echo "error: '" . $error . "',\n";
echo "msg: '" . $msg . "'\n";
echo "}";
?>